package com.leetroll.app.service.impl;

import com.leetroll.app.service.LoginUserService;
import com.leetroll.common.bean.OnlineUser;
import com.leetroll.common.constant.CharConstant;
import com.leetroll.common.constant.RedisConstant;
import com.leetroll.common.constant.SysConstant;
import com.leetroll.common.entity.User;
import com.leetroll.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginUserServiceImpl implements LoginUserService {

    private final RedisUtil redisUtil;

    @Autowired
    public LoginUserServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public void addOnlineUser(User user, String ip, String accessToken, long expiration) {
        OnlineUser onlineUser = new OnlineUser();
        onlineUser.setUserId(user.getId());
        onlineUser.setToken(accessToken);
        onlineUser.setLoginTime(DateUtils.getNowTime());
        onlineUser.setUserName(user.getName());
        onlineUser.setExpireTime(DateUtils.getDateStr(new Date(), expiration));
        //从Redis中获取IP来源
        String jsonResult = redisUtil.get(RedisConstant.IP_SOURCE + CharConstant.SYMBOL_COLON + ip);
        if (StringUtils.isEmpty(jsonResult)) {
            String addresses = IpUtils.getAddresses(SysConstant.IP + SysConstant.EQUAL_TO + ip, SysConstant.UTF_8);
            if (StringUtils.isNotEmpty(addresses)) {
                onlineUser.setLoginLocation(addresses);//登录地址
                redisUtil.setEx(RedisConstant.IP_SOURCE + CharConstant.SYMBOL_COLON + ip, addresses, 24, TimeUnit.HOURS);
            }
        } else {
            onlineUser.setLoginLocation(jsonResult);
        }
        // 将登录的用户存储到在线用户表
        redisUtil.setEx(RedisConstant.LOGIN_TOKEN_KEY + RedisConstant.SEGMENTATION + accessToken, JsonUtils.objectToJson(onlineUser), expiration, TimeUnit.SECONDS);
    }
}